package FileInformation.helpers;


import java.io.*;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: Nobody
 * Date: 25.04.11
 * Time: 21:20
 * To change this template use File | Settings | File Templates.
 */
public class TextLineIgnorer extends AbstractFileHelper implements Serializable {

    private int firstDataRowNumber;
    private final List<Character> typicalSeparators = new LinkedList<Character>();
    private char lineStarter;

    public char getLineStarter() {
        return lineStarter;
    }

    public TextLineIgnorer(File file) {
        super(file);
        typicalSeparators.add(',');
    }

    public int getFirstDataRowNumber() {
        return firstDataRowNumber;
    }

    @Override
    public void execute() throws IOException {
        FileInputStream fstream = new FileInputStream(file);
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));

        firstDataRowNumber = 1;

        //read first line
        String line;
        line = br.readLine();

        if(line == null) {
            throw new IOException("file " + file + " is empty.");
        }
            
        if (isBeginOfFirstDataRow(line)) {
            return;
        }

        if (!Character.isLetterOrDigit(line.charAt(0))) {
            lineStarter = line.charAt(0);
            if (typicalSeparators.contains(line.charAt(0))) {
                typicalSeparators.add(line.charAt(0));
            }

        }

        while ((line = br.readLine()) != null) {
            ++firstDataRowNumber;

            if (isBeginOfFirstDataRow(line)) {
                break;
            }
        }
        br.close();

    }

    private boolean isBeginOfFirstDataRow(String c) {
        if (c.length() < 1) {
            return false;
        }
        int i = 0;
        while (Character.isWhitespace(c.charAt(i))) {
            ++i;
        }
        return (Character.isDigit(c.charAt(i)) || isSeparator(c.charAt(i)) || c.charAt(i) == '-');
    }

    private boolean isSeparator(char c) {
        for (char s : typicalSeparators) {
            if (s == c) {
                return true;
            }
        }
        return false;
    }
}
